package com.yalu.read.word.purchase;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.yalu.entity.PurchaseData;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PurchaseTwoRead {

    public static final Pattern compile = Pattern.compile("((\\$|￥)?(\\d)+(\\.)?(\\d)+)|((\\$|￥)?0)");

    /**
     * 测试Word文件的创建
     *
     * @param args
     */
    public static void main(String[] args) {
        String filePath = "D://yalu//purchase//";  //这里先手动把绝对路径的文件夹给补上。
        List<String> filePaths = new ArrayList<>();
        recursionFile(filePath, filePaths);
        System.out.println("文件数量：" + filePaths.size());
        List<PurchaseData> list = new ArrayList<>();
        String year = filePath.replaceAll("D://yalu//", "").replaceAll("//", "");
        System.out.println(year);
        for (String fileName : filePaths) {
            PurchaseData purchaseData = readWord(fileName, list);
            if (null == purchaseData) {
                System.out.println(fileName);
            }
        }
        String outFileName = "D:\\yalu\\采购单.xlsx";
        writerFils(list, outFileName);
    }

    /**
     * 读Word文件，使用了Wordbox开源项目
     *
     * @param fileName
     */
    public static PurchaseData readWord(String fileName, List<PurchaseData> list) {
        File file = new File(fileName);
        FileInputStream in = null;
        try {
            in = new FileInputStream(fileName);
            // 新建一个Word解析器对象
            XWPFDocument document = new XWPFDocument(in);
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            // 对Word文件进行解析
            String docText = extractor.getText();
            if (StringUtils.hasText(docText)) {
                String[] docTexts = docText.split("\\n|\\r\\n|\\r");
                Queue<PurchaseData> dataQueue = new LinkedList<>();
                for (String lineText : docTexts) {
                    PurchaseData dataNow = dataQueue.poll();
                    PurchaseData purchaseData = new PurchaseData();
                    if (null != dataNow) {
                        BeanUtils.copyProperties(dataNow, purchaseData);
                    }

                    if (StringUtils.hasText(lineText) && lineText.contains("乙方：")) {
                        String[] purchaseNos = lineText.split("乙方：");
                        purchaseData.setPurchaseName(purchaseNos[purchaseNos.length - 1].trim());
                        dataQueue.offer(purchaseData);
                    } else if (StringUtils.hasText(lineText) && lineText.contains("日期：")) {
                        String[] purchaseNames = lineText.split("日期：");
                        purchaseData.setDate(purchaseNames[purchaseNames.length - 1].trim());
                        dataQueue.offer(purchaseData);
                    } else if (StringUtils.hasText(lineText) && lineText.contains("乙方的运费")) {
                        String[] amounts = lineText.split("乙方的运费");
                        getAmount(dataQueue, purchaseData, amounts);
                    } else {
                        dataQueue.offer(purchaseData);
                    }
                    if (StringUtils.hasText(purchaseData.getPurchaseName()) && StringUtils.hasText(purchaseData.getAmount()) && StringUtils.hasText(purchaseData.getDate())) {
                        PurchaseData data = dataQueue.poll();
                        data.setFileName(file.getName());
                        list.add(data);
                        return data;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("读取Word文件" + file.getAbsolutePath() + "生失败！" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
        return null;
    }

    private static void getAmount(Queue<PurchaseData> dataQueue, PurchaseData purchaseData, String[] amounts) {
        String amount = amounts[amounts.length - 1].trim().replace("\t", "");
        Matcher matcher = compile.matcher(amount);
        List<String> amountList = new ArrayList<>();
        while (matcher.find()) {
            amountList.add(matcher.group().trim());
        }
        if (!CollectionUtils.isEmpty(amountList)) {
            purchaseData.setAmount(2 == amountList.size() ? amountList.get(1) : amountList.get(0));
        }
        if(amount.length()>3){
            purchaseData.setCurrency(amount.substring(0,3));
        }
        dataQueue.offer(purchaseData);
    }

    /**
     * 写入文件
     *
     * @param data
     * @param outFileName
     */
    public static void writerFils(List<PurchaseData> data, String outFileName) {
        try {
            ExcelWriter excelWriter = EasyExcel.write(outFileName, PurchaseData.class).build();
            String sheetName = "1";
            List<PurchaseData> list = new ArrayList<>(data.size());
            for (PurchaseData purchaseData : data) {
                PurchaseData billDetailDataExcel = new PurchaseData();
                BeanUtils.copyProperties(purchaseData, billDetailDataExcel);
                list.add(billDetailDataExcel);
            }
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(list, writeSheet);

            // 千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            System.out.println("文件写入失败：" + e.getMessage());
        }
    }

    /**
     * 递归文件
     *
     * @param path
     * @param filePaths
     */
    public static void recursionFile(String path, List<String> filePaths) {
        if (StringUtils.hasText(path)) {
            File file = new File(path);
            for (File f : file.listFiles()) {
                if (f.isDirectory()) {
                    recursionFile(f.getPath(), filePaths);
                } else {
                    if (f.getPath().contains(".doc") || f.getPath().contains(".docx")) {
                        filePaths.add(f.getPath());
                    }
                }
            }
        }
    }
}
